package com.study.producer;

import org.apache.commons.compress.utils.Lists;

import java.util.List;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class Producer {

    private Lock lock;
    private Condition fullCondition;
    private Condition notFullCondition;
    private List<Object> lists;

    public Producer(){
        lock = new ReentrantLock();
        fullCondition = lock.newCondition();
        notFullCondition = lock.newCondition();
        lists = Lists.newArrayList();
    }


    public static void main(String[] args) throws Exception{
        Producer producer = new Producer();
        Thread pro = new Thread(()->{
            try{
                producer.lock.lock();
                while(producer.lists.size()==10){
                    producer.fullCondition.wait();
                }
                producer.lists.add(new Object());
                producer.notFullCondition.signal();
                System.out.println("开始添加。。。"+ producer.lists.size());
            }catch (Exception e){

            }finally {
                producer.lock.unlock();
            }
        });
        pro.start();

        Thread cu = new Thread(()->{
            try{
                producer.lock.lock();
                while(producer.lists.isEmpty()){
                    producer.notFullCondition.wait();
                }
                producer.lists.remove(0);
                producer.fullCondition.signal();
                System.out.println("开始消费。。。"+producer.lists.size());
            }catch (Exception e){

            }finally {
                producer.lock.unlock();
            }
        });
        cu.start();
    }


}
